/*
 * The Yard Utilties - http://www.theyard.net/
 * 
 * Copyright (c) 2008 by Vlideshow, Inc..  All Rights Resrved.
 * 
 * This library is free software; you can redistribute it and/or modify it under the 
 * terms of the GNU Lesser General Public License as published by the Free Software 
 * Foundation; either version 2.1 of the License, or (at your option) any later 
 * version. 
 * 
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY 
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A 
 * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License along 
 * with this library; if not, write to the Free Software Foundation, Inc., 
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 
 */
package net.theyard.components.netconnectionsm
{
  import net.theyard.components.Utils;
  import flash.net.NetConnection;

  /**
   * This class represents the NetConnectionStateMachine#STATE_DISCONNECTED
   * state and implements all transitions.
   *
   * @see ConnectionState
   * @see NetConnectionStateMachine#STATE_DISCONNECTED
   */
  internal class DisconnectedState implements ConnectionState
  {
    private var sm:NetConnectionStateMachine;

    public function DisconnectedState(sm:NetConnectionStateMachine)
    {
      Utils.ytrace("Starting state: " + this.toString());;
      this.sm = sm;
    }


    public function toString():String
    {
      return NetConnectionStateMachine.STATE_DISCONNECTED;
    }

    public function connect(nc:NetConnection, command:String, ...args):void
    {
      // call connect, and send us to the connecting state.
      try
      {
        sm.setUri(command);
        args.unshift(command);
        // change the state before we do the connection.
        sm.gotoState(NetConnectionStateMachine.STATE_CONNECTING);
        nc.connect.apply(nc, args);
      }
      catch (ex:ArgumentError)
      {
        switch (ex.errorID)
        {
          case 2004 :
            Utils.ytrace("Invalid server location: " + command);
            break;
          default :
            break;
        }
        sm.gotoState(NetConnectionStateMachine.STATE_DISCONNECTED);
      }
    }
    public function network_connected(ns:NetConnection):void
    {
      throw new Error(
          "got connected message while disconnected.  state machine is corrupted.");
    }
    public function disconnect(ns:NetConnection):void
    {
      Utils.ytrace("Already disconnected; ignoring request to disconnect");
    }
    public function network_disconnected(nc:NetConnection):void
    {
      Utils.ytrace("successfully disconnected connection");
      sm.setUri(null);
      sm.gotoState(NetConnectionStateMachine.STATE_DISCONNECTED);
    }
  }
}
